<?php

/**
 * 订单模块控制器
 * Class OrderController
 */
class OrderController extends \BaseController
{
    public function __construct()
    {
        /**
         * 订单模块过滤
         */
        $this->beforeFilter('OrderFilter');
    }

    /**
     * 获取订单列表清单
     * 返回json格式:
     * ```
     * [
     *   {
     *     "id": "主键",
     *     "status": 1|2|3,
     *     "orderNum": string,
     *     "receiver": string,
     *     "total": 23.35,
     *     "created_at": date('Y-m-d h:m:s'),
     *     "productList": [
     *     {
     *       "id": 1,
     *       "image": string,
     *       "name": string
     *     }
     *     ]
     *   }
     * ]
     * ```
     *
     * @return Response
     */
    public function index()
    {
        $columns = ['orders.id AS id', 'status_id AS status', 'orderNum', 'receiver', 'total', 'created_at'];
        $productColumns = ['products.id AS id', 'image', 'name'];

        $orders = Order::getOrdersInfo(Auth::user()['id'], $columns);

        foreach ($orders as $key => $order) {
            $order['productList'] = Order::getOrderProducts($order['id'], $productColumns);
            $orders[$key] = $order;
        }

        return Response::json($orders);
    }

    /**
     * 获取创建订单页面
     * @return Response
     */
    public function create()
    {

    }

    /**
     * 创建订单
     * 请求json格式:
     * ```
     * {
     *   "total": 340,
     *   "address": {
     *     "receiver": string,
     *     "phone": string,
     *     "postcode": string,
     *     "deliverAddress": string
     *   },
     *   "productList": [
     *   {
     *     "id": ,
     *     "count": int
     *   }
     *   ]
     * }
     * ```
     * 返回json格式:
     * ```
     * {
     *   "status" => "failure",
     *   "message" => "id"
     * }
     * ```
     * @return Response
     */
    public function store()
    {
        $resq = Input::all();
        $retains = ['total', 'receiver', 'phone', 'postcode', 'deliverAddress'];
        $add = array_only(array_merge($resq, $resq['address']), $retains);

        $validator = $this->getValidatorCheckWith($add);

        if ($validator->fails()) {
            return parent::failResponse($validator->messages());
        } else {
            $add['status_id'] = 1;
            $add['orderNum'] = $this->getOrderNum();
            $add['user_id'] = Auth::user()['id'];
            $add['created_at'] = date('Y-m-d h:m:s');
            $add['updated_at'] = date('Y-m-d h:m:s');
            try {
                $newAdd = Order::create($add);

                OrderProduct::Tsinsert($resq['productList'], $newAdd['id']);
                $cookie = CookieCart::deleteProducts();

                return Response::json(['id' => $newAdd['id']])->withCookie($cookie);
            } catch (Exception $e) {
                return parent::failResponse('内部服务错误');
            }

        }
    }

    /**
     * 获取某一订单详细信息
     * 返回json格式:
     * ```
     * {
     *   "id": ,
     *   "orderNum":  (string),
     *   "status": 1|2|3,
     *   "created_at": ,
     *   "address": {
     *     "receiver": string,
     *     "phone": string,
     *     "postcode": string,
     *     "deliverAddress": string,
     *   },
     *   "productList": {
     *     "id": 1,
     *     "name": "",
     *     "image": "",
     *     "price": 2,
     *     "count": 2
     *   }
     * }
     * ```
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        $columns = ['orders.id AS id', 'status_id AS status', 'orderNum',  'created_at'];
        $productKeys = ['products.id AS id', 'image', 'name', 'price', 'count'];
        $addressKeys = ['receiver', 'phone', 'postcode', 'deliverAddress'];

        $resp = Order::where('id', $id)->select($columns)->get()->toArray()[0];
        $order = Order::find($id)->toArray();

        $resp['address'] = array_only($order, $addressKeys);
        $resp['productList'] = Order::getOrderProducts($id, $productKeys);

        return Response::json($resp);
    }

    /**
     * 获取编辑某一订单页面
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {

    }

    /**
     * 更新某一订单
     * 请求json格式:
     * ```
     * {
     *   "status": int
     * }
     * ```
     * 返回json格式:
     * ```
     * {
     *   "status" => "failure",
     *   "message" => ""
     * }
     * ```
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        $status_id = array_only(Input::all('status'), ['status']);

        $rules = ['status' => 'required|integer|between:1,3'];
        $messages = ['required' => '该选项不能为空', 'integer' => '非整数', 'between' => '越界'];
        $validator = Validator::make($status_id, $rules, $messages);

        if ($validator->fails()) {
            return parent::failResponse('请检查输入是否正确');
        } else {
            $order = Order::findOrFail($id)->update(['status_id' => $status_id['status']]);
            if ($order) {
                return Response::json(['id' => $id]);
            } else {
                return parent::failResponse('内部服务错误');
            }

        }
    }

    /**
     * 删除某一订单
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        try {
            Order::findOrFail($id)->delete();
        } catch (Exception $e) {
            return parent::failResponse('内部服务错误.');
        }

        return parent::successResponse();
    }


    protected function getValidatorCheckWith($filteredData)
    {
        return Validator::make($filteredData, $this->getRules());
    }

    protected function getRules()
    {
        return [
            'total' => 'required',
            'receiver' => 'required|max:50',
            'phone' => 'required|max:11',
            'postcode' => 'required|max:6',
            'deliverAddress' => 'required|max:100',
        ];
    }

    protected function getValidateMsg()
    {
        return [
            'required' => '该选项不能为空',
            'max:50' => '收货人名超过长度限制',
            'max:100' => '收货地址超过长度限制',
            'max:11' => '联系号码超过长度限制',
            'max:6' => '邮编超过长度限制',
            'between' => '越界',
            'integer' => '非整数'
        ];
    }

    /**
     * 订单号生成
     * @return string
     */
    private function getOrderNum()
    {
        $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
        return $yCode[(intval(date('Y')) - 1971)%10]
        . strtoupper(dechex(date('m')))
        . date('d') . substr(time(), -5)
        . substr(microtime(), 2, 5)
        . sprintf('%02d', rand(0, 99));
    }
}
